package pkg

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"user_srv/basic/config"
)

func GetAccessToken() (string, error) {
	url := "https://aip.baidubce.com/oauth/2.0/token"
	postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", config.AppCong.BaiduFace.ApiKey, config.AppCong.BaiduFace.SecretKey)

	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData))
	if err != nil {
		return "", fmt.Errorf("获取Token失败: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("读取Token响应失败: %w", err)
	}

	var tokenResp map[string]interface{}
	if err = json.Unmarshal(body, &tokenResp); err != nil {
		return "", fmt.Errorf("解析Token响应失败: %w，响应内容: %s", err, string(body))
	}

	// 处理API错误
	if errMsg, ok := tokenResp["error"].(string); ok && errMsg != "" {
		desc, _ := tokenResp["error_description"].(string)
		return "", fmt.Errorf("Token接口报错: %s - %s", errMsg, desc)
	}

	// 提取Token（类型校验）
	accessToken, ok := tokenResp["access_token"].(string)
	if !ok {
		return "", fmt.Errorf("Token格式异常，响应: %s", string(body))
	}

	return accessToken, nil
}
